package com.example.chatgpt.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.example.chatgpt.MyApplication;
import com.example.chatgpt.R;
import com.example.chatgpt.bean.ApiData;
import com.example.chatgpt.options.GlideApp;
import com.example.chatgpt.util.CloseKeyBoardUtil;
import com.example.chatgpt.util.PxUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PaintingFragment extends Fragment implements View.OnClickListener {


    private ImageView iv_picture;
    OkHttpClient okHttpClient = new OkHttpClient();
    public static final MediaType JSON
            = MediaType.get("application/json; charset=utf-8");
    private EditText et_desc_painting;
    //图片链接
    private String result;
    //生成图片的位图对象
    private Bitmap bitmap = null;
    private EditText et_input_key;
    private SharedPreferences tokenPreferences;
    private SharedPreferences.Editor tokenEdit;
    //保存的token
    private String token;

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_painting, container, false);
        view.findViewById(R.id.btn_create_picture).setOnClickListener(this);
        view.findViewById(R.id.btn_save_picture).setOnClickListener(this);
        view.findViewById(R.id.ib_painting_key).setOnClickListener(this);
        iv_picture = view.findViewById(R.id.iv_create_picture);
        et_desc_painting = view.findViewById(R.id.et_input_desc_painting);

        //利用sharedPreference保存token
        tokenPreferences = getActivity().getSharedPreferences("token", Context.MODE_PRIVATE);
        tokenEdit = tokenPreferences.edit();

        reLoad();
        Log.d("guaimiao", token);

        return view;
    }

    //重新加载token
    private void reLoad() {
        String reToken = tokenPreferences.getString("token", "");
        if (!reToken.equals("")) {
            token = reToken;
        } else {
            token = "";
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_create_picture:
                CloseKeyBoardUtil.hideOneInputMethod(getActivity(), view);
                //判断token是否为空
                if (!token.equals("")) {
                    String desc = et_desc_painting.getText().toString().trim();
                    //判断描述是否为空
                    if (!desc.equals("")) {
                        callApiPainting(desc);
                    } else {
                        Toast.makeText(getContext(), "请输入你的描绘!", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "请输入密钥token!", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_save_picture:
                //android9.0以上
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    saveQUp(bitmap, getContext(), "guaimiao.png", 100);
                }
                break;
            case R.id.ib_painting_key:
                initPaintingKeyDialog();
                break;
        }

    }

    //密钥底部弹窗
    private void initPaintingKeyDialog() {
        //创建dialog对象
        Dialog bottomDialog = new Dialog(getContext(), R.style.BottomDialog);
        //获取布局文件
        View view = LayoutInflater.from(getContext()).inflate(R.layout.activity_input_api_key, null);
        //加入布局
        bottomDialog.setContentView(view);
        //设置参数
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels;
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
        //事件处理
        et_input_key = view.findViewById(R.id.et_input_key);
        view.findViewById(R.id.ib_confirm).setOnClickListener(view1 -> {
            Toast.makeText(getContext(), "修改token成功!", Toast.LENGTH_SHORT).show();
            token = et_input_key.getText().toString().trim();
            tokenEdit.putString("token", token);
            tokenEdit.commit();
            bottomDialog.dismiss();
        });
    }


    //请求绘画的api
    void callApiPainting(String desc) {

        JSONObject jsonBody = new JSONObject();
        try {
            /* jsonBody.put("prompt", desc);*/
            /*jsonBody.put("n", 1);
            jsonBody.put("size", "256×256");*/
            jsonBody.put("question", desc);
            jsonBody.put("token", token);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("guaimiao", jsonBody.toString());
        RequestBody requestBody = RequestBody.create(jsonBody.toString(), JSON);

        Request request = new Request.Builder()
                /*.url("https://api.openai.com/v1/images/generations")*/

                /*.header("Authorization", "Bearer " + apiKey)*/
                /*.addHeader("Content-Type", "application/json")*/
                .url("https://lytcreate.com/api/paint/")
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d("guaimiao", "failed due to " + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        Log.d("guaimiao", jsonObject.toString());
                        /*JSONArray dataArray = jsonObject.getJSONArray("data");
                        Log.d("guaimiao", dataArray.toString());
                        String url = dataArray.getJSONObject(0).getString("url");*/
                        String str = jsonObject.getString("answer");
                        int firstIndex = str.indexOf("h");
                        int lastIndex = str.lastIndexOf("s");
                        if (firstIndex != -1 && lastIndex != -1) {
                            result = str.substring(firstIndex, lastIndex);
                            Log.d("guaimiao", result);
                            //在主线程中获取网络请求的图片的target对象
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    FutureTarget<Bitmap> target = GlideApp.with(getActivity())
                                            .asBitmap()
                                            .load(result.trim())
                                            .applyAvatar(144 * 6)
                                            .submit();
                                    //在子线程中获取bitmap对象 并在主线程中设置图片
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                bitmap = target.get();
                                                getActivity().runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        iv_picture.setImageBitmap(bitmap);
                                                    }
                                                });
                                            } catch (ExecutionException e) {
                                                e.printStackTrace();
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).start();
                                }
                            });
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    //将请求的图片保存到系统相册
    // Android Q 以上
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public void saveQUp(Bitmap image, Context context, String fileName, int quality) {
        if (bitmap == null) {
            Toast.makeText(getContext(), "你还没有生成图片", Toast.LENGTH_SHORT).show();
        } else {
            // 文件夹路径
            String imageSaveFilePath = Environment.DIRECTORY_DCIM + File.separator + "guaimiao";
            Log.i("TAG", "文件夹目录 >>> " + imageSaveFilePath);
            //mkdir(imageSaveFilePath);
            // 文件名字
            Log.d("TAG", "文件名字 >>> " + fileName);
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.TITLE, fileName);
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
            contentValues.put(MediaStore.MediaColumns.DATE_TAKEN, fileName);
            //该媒体项在存储设备中的相对路径，该媒体项将在其中保留
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, imageSaveFilePath);
            Uri uri = null;
            OutputStream outputStream = null;
            ContentResolver localContentResolver = context.getContentResolver();
            try {
                uri = localContentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                outputStream = localContentResolver.openOutputStream(uri);
                // Bitmap图片保存
                // 1、宽高比例压缩
                // 2、压缩参数
                image.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
                if (uri != null) {
                    localContentResolver.delete(uri, null, null);
                }
            } finally {
                image.recycle();
                Toast.makeText(getContext(), "已保存到相册!", Toast.LENGTH_SHORT).show();
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


}